package com.cch.cooperation.api.zone.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cch.cooperation.api.common.util.NumUtil;
import com.cch.cooperation.api.zone.dto.ZoneEditDTO;
import com.cch.cooperation.biz.common.util.BeanUtilEx;
import com.cch.cooperation.common.util.SnowflakeIdUtil;
import com.cch.cooperation.dao.zone.dto.ZoneDTO;
import com.cch.cooperation.common.exception.BizException;
import com.cch.cooperation.dao.zone.enums.ZoneUserEnum;
import com.cch.cooperation.dao.zone.mapper.ZoneMapper;
import com.cch.cooperation.dao.zone.model.Zone;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ZoneServiceImpl {

    @Resource
    private ZoneMapper mapper;
    @Resource
    private ZoneUserServiceImpl zoneUserService;
    @Resource
    private ZoneUserApplyServiceImpl zoneUserApplyService;

    public List<ZoneDTO> listByUserId(String userId) {
        if (StrUtil.isEmpty(userId)) {
            throw new BizException("用户id不能位空");
        }
        return mapper.queryList(userId);
    }

    public List<ZoneDTO> queryList(String userId, Integer type) {
        if (StrUtil.isEmpty(userId)) {
            throw new BizException("用户id不能位空");
        }
        List<ZoneDTO> result = mapper.queryList(userId);
        if (Objects.nonNull(type)) {
            result = result.stream().filter(o -> type.equals(o.getType())).collect(Collectors.toList());
        }
        for (ZoneDTO item : result) {
            item.setJoinCode(buildJoinCode(item.getId()));
            item.setJoinWord(buildJoinWord(item.getId(), item.getName()));
            item.setUsers(zoneUserService.queryList(item.getId()));
            item.setZoneUserApplyCount(zoneUserApplyService.getWaitAuditCount(item.getId()));
        }
        return result;
    }

    public List<Zone> queryByType(Integer type) {
        LambdaQueryWrapper<Zone> query = new LambdaQueryWrapper<>();
        query.eq(Zone::getType, type);
        return mapper.selectList(query);
    }

    public ZoneDTO getByJoinCode(String joinCode) {
        if (StrUtil.isEmpty(joinCode)) {
            throw new BizException("邀请码不能为空");
        }
        return getById(getIdByJoinCode(joinCode));
    }

    public String buildJoinCode(String id) {
        return "Td://#" + NumUtil.base10To32(Long.valueOf(id)) + "&";
    }

    public String buildJoinWord(String id, String zoneName) {
        return "复制星球口令：" + buildJoinCode(id) + " ，" + zoneName + "星球等待你的加入~";
    }

    public String getIdByJoinCode(String joinCode) {
        String hex = joinCode.replace("Td://#", "").replace("&", "");
        return NumUtil.base32To10(hex).toString();
    }

    public ZoneDTO getById(String id) {
        if (StrUtil.isEmpty(id)) {
            throw new BizException("id不能为空");
        }
        ZoneDTO result = BeanUtilEx.copy(mapper.selectById(id), ZoneDTO.class);
        if (Objects.isNull(result)) {
            return null;
        }
        result.setJoinCode(buildJoinCode(result.getId()));
        result.setJoinWord(buildJoinWord(result.getId(), result.getName()));
        result.setUsers(zoneUserService.queryList(result.getId()));
        result.setZoneUserApplyCount(zoneUserApplyService.getWaitAuditCount(result.getId()));
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public ZoneDTO add(@Valid ZoneEditDTO req) {
        // 添加空间
        Zone zone = BeanUtilEx.copy(req, Zone.class);
        zone.setId(SnowflakeIdUtil.getIdStr());
        zone.setCreateTime(new Date());
        zone.setCreateUserId(req.getUpdateUserId());
        mapper.insert(zone);
        // 添加空间管理员
        zoneUserService.add(zone.getId(), zone.getCreateUserId(), ZoneUserEnum.RoleType.ADMIN.value);
        return getById(zone.getId());
    }

    public ZoneDTO updateById(@Valid ZoneEditDTO req) {
        if(StrUtil.isEmpty(req.getId())) {
            throw new BizException("用户id不能位空");
        }
        Zone zone = BeanUtilEx.copy(req, Zone.class);
        zone.setUpdateTime(new Date());
        mapper.updateById(zone);
        return getById(req.getId());
    }

    public void deleteById(String id) {
        if (StrUtil.isEmpty(id)) {
            throw new BizException("id不能为空");
        }
        mapper.deleteById(id);
    }

    public Map<String, Zone> getMapByIds(List<String> ids) {
        if (ids.isEmpty()) {
            return new HashMap<>();
        }
        List<Zone> list = mapper.selectBatchIds(ids);
        return list.stream().collect(Collectors.toMap(Zone::getId, o -> o));
    }

}
